package org.domain.sigerec.session;

import java.util.ArrayList;
import java.util.List;

import javax.faces.event.ActionEvent;

import org.domain.sigerec.entity.Cabine;
import org.domain.sigerec.entity.Cliente;
import org.domain.sigerec.entity.Reserva;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.framework.EntityHome;

@Name("reservaHome")
public class ReservaHome extends EntityHome<Reserva>
{

    /**
	 * 
	 */
	private static final long serialVersionUID = 3321330278278245517L;
	@RequestParameter 
    Long reservaId;
	
	private Cabine cabine = new Cabine();
	
	private Cliente cliente = new Cliente();
	
    @Override
    public Object getId() 
    { 
        if (reservaId==null)
        {
            return super.getId();
        }
        else
        {
            return reservaId;
        }
    }
    
    @Override @Begin
    public void create() {
        super.create();
    }
    
	@Override
	public String persist() {
		saveCabine();
		saveCliente();
		return super.persist();
	}
	
	public Cabine getCabine() {
		return cabine;
	}

	public void setCabine(Cabine cabine) {
		this.cabine = cabine;
	}

	public Cliente getCliente() {
		return cliente;
	}

	public void setCliente(Cliente cliente) {
		this.cliente = cliente;
	}

	public void saveCabine() {		
		
        if(instance.getCabines() == null) {
        	instance.setCabines(new ArrayList<Cabine>());
        }
        if(!instance.getCabines().contains(cabine)){
        	instance.getCabines().add(cabine);
        }
        cabine = new Cabine();
	}
	
	public void saveCliente() {		
		
        if(instance.getClientes() == null) {
        	instance.setClientes(new ArrayList<Cliente>());
        }
        if(!instance.getClientes().contains(cliente)){
        	instance.getClientes().add(cliente);
        }
        cliente = new Cliente();
	}
	
	
	public List<Cabine> getCabines(){
		String query = "from Cabine ";
		
		if(instance.getCruzeiro() != null){
		
			query += " c WHERE c.navio.id = :idNavio";
			return getEntityManager().createQuery(query)
			.setParameter("idNavio", instance.getCruzeiro().getNavio().getId())
			.getResultList();
		}
		
		return getEntityManager().createQuery(query).getResultList();
	}
	
}
